package com.fys.order.controller;

import com.fys.order.utils.ResultVOUtil;
import com.fys.order.vo.ResultVO;
import com.fys.product.client.ProductClient;
import com.fys.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @author: fys
 * @description: 调用服务的三种方式（这段代码可以去掉）
 * @create: 2020-07-24 16:47
 **/
@Slf4j
@RestController
@RequestMapping("/client")
public class ClientController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ProductClient productClient;

    @GetMapping("/getProductMsg")
    public String getProductMsg(){
        // 第一种方式：使用RestTemplate
//        RestTemplate restTemplate = new RestTemplate();
//        String result = restTemplate.getForObject("http://localhost:8081/server/msg", String.class);
//        return result;

        // 第二种方式：LoadBalanceClient
//        RestTemplate restTemplate = new RestTemplate();
        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
        String url = String.format("http:%s:%s", serviceInstance.getHost(),serviceInstance.getPort()+"/server/msg");
        String result = restTemplate.getForObject(url, String.class);
        return result;

        // 第三种方式：RestTemplate和@LoadBalanced配置的使用
//        String result = restTemplate.getForObject("http://PRODUCT/server/msg", String.class);
//        return result;
    }

    @GetMapping("/getProductList")
    public ResultVO<List<ProductInfoOutput>> getProductList(){
        List<ProductInfoOutput> productInfoOutputs = productClient.listForOrder(Arrays.asList("157875196366160022"));
        log.info("response:{}", productInfoOutputs);
        return ResultVOUtil.success(productInfoOutputs);
    }




}
